package presentation;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JProgressBar;

@SuppressWarnings("serial")
public class ApfelMannFrame extends JFrame {

	private ApfelMannPanel apfelMannPanel = new ApfelMannPanel();
	private JProgressBar progressBar = new JProgressBar(0, 100);

	private int startX;

	private int startY;

	public ApfelMannFrame() {
		setLayout(new BorderLayout());

		add(apfelMannPanel, BorderLayout.CENTER);
		add(progressBar, BorderLayout.SOUTH);

		apfelMannPanel.addMouseListener(new MouseAdapter() {

			@Override
			public void mousePressed(MouseEvent e) {
				startX = e.getX();
				startY = e.getY();

				apfelMannPanel.setZoomMode(true);
			}

			@Override
			public void mouseReleased(MouseEvent e) {
				SelectionBox selectionBox = new SelectionBox(startX, startY, e
						.getX(), e.getY());

				apfelMannPanel.setSelectionBox(selectionBox);

				apfelMannPanel.setNewBounds(selectionBox.getFromX(),
						selectionBox.getFromX() + selectionBox.getLength(),
						selectionBox.getFromY(), selectionBox.getFromY()
								+ selectionBox.getLength());

				apfelMannPanel.setZoomMode(false);

				ProgressWorker pw = new ProgressWorker(apfelMannPanel);
				pw.addPropertyChangeListener(new PropertyChangeListener() {

					@Override
					public void propertyChange(PropertyChangeEvent e) {
						if ("progress".equals(e.getPropertyName())) {
							progressBar.setIndeterminate(false);
							progressBar.setValue((Integer) e.getNewValue());
						}

					}
				});
				pw.execute();
			}
		});

		apfelMannPanel.addMouseMotionListener(new MouseMotionAdapter() {

			@Override
			public void mouseDragged(MouseEvent e) {

				apfelMannPanel.setSelectionBox(new SelectionBox(startX, startY,
						e.getX(), e.getY()));
				apfelMannPanel.repaint();
			}
		});

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setResizable(false);
		pack();
		setVisible(true);
		
		ProgressWorker pw = new ProgressWorker(apfelMannPanel);
		pw.addPropertyChangeListener(new PropertyChangeListener() {

			@Override
			public void propertyChange(PropertyChangeEvent e) {
				if ("progress".equals(e.getPropertyName())) {
					progressBar.setIndeterminate(false);
					progressBar.setValue((Integer) e.getNewValue());
				}

			}
		});
		pw.execute();
	}
}
